<template>
	<view>
		<view>
			<table-title content="中介结佣办理表详情"></table-title>
			<view class="record-id">单号：{{processNo}}</view>
			<view class="in-center">
				<small-title content="基本资料"></small-title>
				<view class="state-bar">
					<view class="state-msg">{{state}}</view>
				</view>
			</view>
			<view class="item-table">
				<view-item name="申请人" :value="createInfo.name"></view-item>
				<view-item name="电话" :value="createInfo.phone" :isLast="true"></view-item>
			</view>
			<small-title :isNeed="true" content="租赁意向书"></small-title>
			<view class="download-text" @click="downloadFile(0)">{{fileList[0].fileName}}</view>
			<button v-if="status===-1" class="add-button" @click="uploadFile(0)">上传文件</button>
			<small-title :isNeed="true" content="结佣申请结算书"></small-title>
			<view class="download-text" @click="downloadFile(1)">{{fileList[1].fileName}}</view>
			<button v-if="status===-1" class="add-button" @click="uploadFile(1)">上传文件</button>
			<small-title :isNeed="true" content="分成信息"></small-title>
			<view v-if="isReady" style="margin-left: 80rpx;margin-right: 50rpx;">
				<uni-forms :modelValue="divideInformation">
					<uni-forms-item required label="自己占比" name="self">
						<uni-easyinput :disabled="status!==-1" name="name" style="background-color: #ffffff;" type="text" v-model="divideInformation.self" />
					</uni-forms-item>
					<uni-forms-item required label="中介占比" name="knot">
						<uni-easyinput :disabled="status!==-1" name="name" style="background-color: #ffffff;" type="text" v-model="divideInformation.knot" />
					</uni-forms-item>
					<uni-forms-item required label="简要说明" name="desc">
						<uni-easyinput :disabled="status!==-1" name="name" style="background-color: #ffffff;" type="text" v-model="divideInformation.desc" />
					</uni-forms-item>
				</uni-forms>
			</view>
			<view v-if="state == '待申请'">
				<small-title :isNeed="true" content="选择运营主管审批"></small-title>
				<view class="small-title">
					<select-lay :value="opeUser" name="name" :options="datalistOpe" @selectitem="selectitemOpe" :disabled="false"></select-lay>
				</view>
			</view>
			<view v-if="status >= 0">
				<small-title :isNeed="true" content="选择运营主管审批"></small-title>
				<view class="small-title">
					<select-lay :value="opeUser" name="name" :options="datalistOpe" @selectitem="selectitemOpe" :disabled="true"></select-lay>
				</view>
			</view>
			<view v-if="status >= 0 && status < 4">
				<small-title :isNeed="true" v-if="status >= 0 && status < 4" content="佣金付款申请单"></small-title>
				<view v-if="status >= 0 && status < 4" class="download-text" @click="downloadFile(2)">{{fileList[2].fileName}}</view>
				<button v-if="status == 0 && userRightDetail.knotCommission.opeVerRight" class="add-button" @click="uploadFile(2)">上传文件</button>
				<small-title :isNeed="true" v-if="status > 0 || (status == 0 && userRightDetail.knotCommission.opeVerRight)" content="选择项目总监审批"></small-title>
				<view v-if="status > 0 || (status == 0 && userRightDetail.knotCommission.opeVerRight)" class="small-title">
					<select-lay :value="leaderUser" name="name" :options="datalistLeader" @selectitem="selectitemLeader" :disabled="status!==0"></select-lay>
				</view>
			</view>
			<view v-if="(status > 1 && status < 4) || (status == 1 && userRightDetail.knotCommission.leaderVerRight)">
				<small-title :isNeed="true" v-if="status >= 1" content="选择财务主管审批"></small-title>
				<view v-if="status >= 1" class="small-title">
					<select-lay :value="financeUser" name="name" :options="datalistFinance" @selectitem="selectitemFinance" :disabled="status!==1"></select-lay>
				</view>
			</view>
			<small-title v-if="status >= 0" content="处理进度"></small-title>
			<proccess-bar v-if="processFlag" :proccessList="proccessListDefult"></proccess-bar>
			<view v-if="status===-1" class="mix-button">
				<view class="left-part">
					<button class="left-button" @click="addOrder">立即申请</button>
				</view>
				<view class="right-part">
					<button class="right-button" @click="back">返回</button>
				</view>
			</view>
			<view v-if="status===0 && this.userRightDetail.knotCommission.opeVerRight" class="mix-button">
				<view class="left-part">
					<button class="left-button" @click="verify(1)">审核通过</button>
				</view>
				<view class="right-part">
					<button class="right-button" @click="open(0)">驳回申请</button>
				</view>
			</view>
			<view v-if="status===1 && this.userRightDetail.knotCommission.leaderVerRight" class="mix-button">
				<view class="left-part">
					<button class="left-button" @click="verify(2)">审核通过</button>
				</view>
				<view class="right-part">
					<button class="right-button" @click="open(1)">驳回</button>
				</view>
			</view>
			<view v-if="status===2 && this.userRightDetail.knotCommission.finanVerRight" class="mix-button">
				<view class="left-part">
					<button class="left-button" @click="verify(3)">审核通过</button>
				</view>
				<view class="right-part">
					<button class="right-button" @click="open(2)">驳回</button>
				</view>
			</view>
			<view style="height: 200rpx;"></view>
		</view>
		<uni-popup ref="popup" :mask-click="true" type="dialog">
		    <uni-popup-dialog  v-if="status===0" mode="input" message="成功消息" title="请输入驳回理由" :duration="2000" :before-close="true" @close="close" @confirm="confirm"></uni-popup-dialog>
			<uni-popup-special v-if="status===1 || status===2" mode="input" message="成功消息" title="请输入驳回理由" :duration="2000" :before-close="true" @close="close" @confirm="confirm"></uni-popup-special>
		</uni-popup>
		<l-file 
		    ref="lFile" 
			@up-success="upSuccess"
		></l-file>
	</view>
</template>		

<script>
	import {
		ONLINE_SERVER_ADDRESS_BASE_2,
		syncGetOrder,
		syncGetSysUsr,
		syncGetSysUsrInfo,
	} from "../../../util/network.js"
	import {
		processHistoryList
	} from "../../../util/common.js"
	export default{
		data() {
			return {
				divideInformation:{'self':'','knot':'','desc':''},
				myInfo:'',
				createInfo:{'name':'','company':'','phone':''},
				processFlag:false,
				isReady:false,
				status:-1,
				recordId: -1,
				processNo:'待分配',
				state: '',
				userMsg:{'userName':'','userPhone':'','userCompany':'','userBuilding':'',
					'userFloor':'','userRoom':''},
				goodList:[],
				fileList:[{'fileName':'租赁意向书.docx', 'fileId':-1},
						  {'fileName':'结佣申请结算书.docx', 'fileId':-1},
						  {'fileName':'佣金付款申请单.docx', 'fileId':-1}
				],//'租赁合同.pdf','租赁合同.pdf'
				nopassReasons:'审核通过',
				proccessListDefult:[],
				token:'',
				endDate:'',
				fileType:0, //0:租赁意向书 1:结佣申请结算书 2:佣金付款申请单
				//模拟数据列表
				datalistOpe: [],
				//模拟初始数据
				opeUser: "",
				//模拟数据列表
				datalistLeader: [],
				//模拟初始数据
				leaderUser: "",
				datalistFinance: [],
				//模拟初始数据
				financeUser: "",
				returnType:0,
			}
		},
		methods: {
			selectitemOpe(index, item) {
				console.log(item)
				if (index >= 0) {
					this.opeUser = item.value;
				} else {
					this.opeUser = ""
				}
			},
			selectitemLeader(index, item) {
				console.log(item)
				if (index >= 0) {
					this.leaderUser = item.value;
				} else {
					this.leaderUser = ""
				}
			},
			selectitemFinance(index, item) {
				console.log(item)
				if (index >= 0) {
					this.financeUser = item.value;
				} else {
					this.financeUser = ""
				}
			},

			open(type) {
				this.returnType = type
				this.$refs.popup.open()
			},
			/**
			 * 点击取消按钮触发
			 * @param {Object} done
			 */
			close(value) {
				// TODO 做一些其他的事情，before-close 为true的情况下，手动执行 close 才会关闭对话框
				// ...
				if(this.returnType == 0){
					this.$refs.popup.close()
				}else{
					if(value == ""){
						uni.showModal({
							content:'理由不能为空',
							showCancel:false
						});
						this.$refs.popup.close()
					}else{
						if(this.returnType == 1){
							this.nopassReasons = "总监已驳回到运营，理由：" + value
						}
						if(this.returnType == 2){
							this.nopassReasons = "财务主管已驳回到运营，理由：" + value
						}
						this.verify(0)
						this.$refs.popup.close()
					}
				}
			},
			/**
			 * 点击确认按钮触发
			 * @param {Object} done
			 * @param {Object} value
			 */
			confirm(value) {
				if(value == ""){
					uni.showModal({
						content:'理由不能为空',
						showCancel:false
					});
					this.$refs.popup.close()
				}else{
					if(this.returnType == 0){
						this.nopassReasons = "运营主管已驳回申请，理由：" + value
					}
					if(this.returnType == 1){
						this.nopassReasons = "总监已驳回申请，理由：" + value
					}
					if(this.returnType == 2){
						this.nopassReasons = "财务已驳回申请，理由：" + value
					}
					this.verify(4)
					this.$refs.popup.close()
				}
			},
			
			upSuccess(e){
				console.log(e)
				if(this.fileType == 4){
					this.fileList[this.fileType].fileName.push(e.fileName)
					this.fileList[this.fileType].fileId.push(e.data)
				}else{
					this.fileList[this.fileType].fileName = e.fileName
					this.fileList[this.fileType].fileId = e.data
				}

			},
			
			uploadFile(status){
				this.fileType = status
				this.$refs.lFile.upload({
				    // #ifdef APP-PLUS
				    //（app端必传）nvue页面使用时请查阅nvue获取当前webview的api，当前示例为vue窗口
				    currentWebview: this.$mp.page.$getAppWebview(),
				    // #endif
				    //替换为你的上传接口地址
				    url: `${ONLINE_SERVER_ADDRESS_BASE_2}/file/upload`,
				    // 服务端接收附件的key
				    name: 'file',
				    //根据你接口需求自定义 (优先不传content-type,安卓端无法收到参数再传)
				    header: {
						'Authorization': this.token,
				        // 'Authorization': 'bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySW5mbyI6eyJ1c2VyTmFtZSI6',
				        // 'uid': '27682',
				        // 'client': 'app',
				        // 'accountid': 'DPOA9487'
				    },
				
				    // 限制选择附件的大小上限，默认10M
				    // maxSize: 20,
				
				    // 若需要在body单独添加附件名或附件大小如下方式传入组件：
				    // addName: '后端要的附件名称字段key,此处请勿写name的同值如(file)，会覆盖name',
				    // addSize: '后端要的附件大小字段key'
				
				    // body参数直接写key,value,如：
				    // date: '2020-1-1',
				    // key2: 'value2',
				});
			},
			
			downloadFile(fileType,index){
				let fileId = 0
				let errMsg = ""
				fileId = this.fileList[fileType].fileId
				switch(fileType) {
					 case 0:
						errMsg = "待申请人上传"
						break;
					 case 1:
						errMsg = "待申请人上传"
						break;
					 case 2:
						errMsg = "待运营主管上传"
						break;
				}
				if(!(parseInt(fileId) > 0)){
					uni.showModal({
						content:errMsg,
						showCancel:false
					})
					return 0
				}
				this.$refs.lFile.download({
					url:`${ONLINE_SERVER_ADDRESS_BASE_2}/file/download/` + fileId,
					token:this.token,
				})
				.then(path=>{
				    // 打开文件
				    this.$refs.lFile.open(path);
				});
			},
			
			verify(status){
				let userId = 0
				let fileId = 0
				let commentMsg = ''
				console.log("[info]","运营主管审核：" + this.recordId)
				switch(status) {
					 case 0:
						commentMsg = this.nopassReasons
						break;
					 case 1:
						fileId = parseInt(this.fileList[2].fileId)
						userId = parseInt(this.leaderUser)
						commentMsg = "运营审核通过"
						break;
					 case 2:
						userId = parseInt(this.financeUser)
						commentMsg = "总监审核通过"
						break;
					 case 3:
						commentMsg = "财务审核通过"
						break;
					 case 4:
						commentMsg = this.nopassReasons
						break;
				}
				if(status == 1){
					if(!(fileId > 0)){
						uni.showModal({
							content:'请上传佣金付款申请单',
							showCancel:false
						})
						return 0
					}
				}
				if(!(status == 4 || status == 0 || status == 3)){
					if(!(userId > 0)){
						uni.showModal({
							content:'请选择审批人',
							showCancel:false
						})
						return 0
					}
				}

				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE_2}/commission-payment/verify/` + this.recordId,
					header: {
						'Authorization': this.token,
					},
					data: {
						status:status,
						userId:userId,
						fileId:fileId,
						commentMsg:commentMsg,                       //操作信息
					},
					method:'POST',
					success: function (res) {
						console.log("审核",res);
						if(res.data.code == 200){
							uni.navigateBack()
						}
					},
					fail: (res) => {
						console.log("审核调用失败")
					}
				})
			},
			
			addOrder(){
				if(this.opeUser == ''){
					uni.showModal({
						content:'请选择运营主管',
						showCancel:false
					})
					return 0
				}
				if(this.fileList[0].fileId == -1 || this.fileList[1].fileId == -1){
					uni.showModal({
						content:'请上传租赁意向书及结佣申请结算书',
						showCancel:false
					})
					return 0
				}
				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE_2}/commission-payment/add`,
					header: {
						'Authorization': this.token,
					},
					data: {
						leaseLetterId:this.fileList[0].fileId,
						settlementStatementId:this.fileList[1].fileId,
						divideInformation:JSON.stringify(this.divideInformation),
						userId:parseInt(this.opeUser),
						commentMsg: '招商发起结佣申请'                       //操作信息
					},
					method:'POST',
					success: function (res) {
						console.log("发起结佣成功",res);
						if(res.data.code == 200){
							uni.navigateBack()
						}
					},
					fail: (res) => {
						console.log("发起结佣调用失败")
					}
				})
			},
			
			getOrder(){
				let a = syncGetOrder("commission-payment/show/" + this.recordId)
				 a.then((res)=>{
					 console.log("异步",res)
					 if(res.data.code == 200){
						 console.log("详细",res.data.data)
						 this.createInfo.name = res.data.data.createUserInfo.name
						 this.createInfo.company = res.data.data.createUserInfo.workAddress
						 this.createInfo.phone = res.data.data.createUserInfo.phone
						 this.status = parseInt(res.data.data.status)
						 switch(this.status) {
							 case 0:
								this.state = "待运营审核"
								break;
							 case 1:
								this.state = "待总监审核"
								break;
							 case 2:
								this.state = "待财务审核"
								break;
							 case 3:
								this.state = "审核完毕"
								break;
							 case 4:
								this.state = "已驳回申请"
								break;
						 	 default:
						 		this.state = "全部"
						 } 
						 this.processNo = res.data.data.processNo
						 this.divideInformation = JSON.parse(res.data.data.divideInformation)
						 this.fileList[0].fileId = res.data.data.leaseLetterId
						 this.fileList[1].fileId = res.data.data.settlementStatementId
						 this.fileList[2].fileId = res.data.data.paymentApplicationsId
						 this.proccessListDefult = processHistoryList(res.data.data.processDetail)
						 this.processFlag = true
						 if(this.status >= 0 && this.status < 4){      //如果管家已指派了运营主管，则查询当前主管信息
							 let b = syncGetSysUsrInfo("systemuser/show/" + parseInt(res.data.data.operationSupervisorId));
							 b.then((v)=>{
							 	 if(v.data.code == 200){
							 		let temp = {label: "",value: ""}
							 		temp.label = v.data.data.name
							 		temp.value = res.data.data.operationSupervisorId.toString()
							 		this.datalistOpe.push(temp)
							 		this.opeUser = temp.value
							 		this.$forceUpdate()
							 	}
							 })
						 }
						 if(this.status >= 1 && this.status < 4){
							 let b = syncGetSysUsrInfo("systemuser/show/" + parseInt(res.data.data.projectDirectorId));
							 b.then((v)=>{
							 	 if(v.data.code == 200){
							 		let temp = {label: "",value: ""}
							 		temp.label = v.data.data.name
							 		temp.value = res.data.data.projectDirectorId.toString()
							 		this.datalistLeader.push(temp)
							 		this.leaderUser = temp.value
							 		this.$forceUpdate()
							 	}
							 })
						 }
						 if(this.status >= 2 && this.status < 4){
							 let b = syncGetSysUsrInfo("systemuser/show/" + parseInt(res.data.data.financeSupervisorId));
							 b.then((v)=>{
							 	 if(v.data.code == 200){
							 		let temp = {label: "",value: ""}
							 		temp.label = v.data.data.name
							 		temp.value = res.data.data.financeSupervisorId.toString()
							 		this.datalistFinance.push(temp)
							 		this.financeUser = temp.value
							 		this.$forceUpdate()
							 	}
							 })
						 }
						 if(this.status == 0){     //如果是主管待选择总监审核状态，则查询总监权限的所有员工
							 var areaId = this.myInfo.area_id
							 console.log("查询工作人员",areaId)
							 let a = syncGetSysUsr("systemuser/area-auth/users", areaId, 13);
							 a.then((res)=>{
							 	 if(res.data.code == 200){
							 		let resList = res.data.data.systemUserList
							 		resList.forEach((item,key) => {
							 			let temp = {label: "",value: ""}
							 			temp.label = item.name
							 			temp.value = item.id.toString()
							 			this.datalistLeader.push(temp)
							 		});
							 		this.$forceUpdate()
							 	}
							 })
						 }
						 if(this.status == 1){     //如果是总监待选择财务审核状态，则查询财务权限的所有员工
							 var areaId = this.myInfo.area_id
							 console.log("查询工作人员",areaId)
							 let a = syncGetSysUsr("systemuser/area-auth/users", areaId, 5);
							 a.then((res)=>{
							 	 if(res.data.code == 200){
							 		let resList = res.data.data.systemUserList
							 		resList.forEach((item,key) => {
							 			let temp = {label: "",value: ""}
							 			temp.label = item.name
							 			temp.value = item.id.toString()
							 			this.datalistFinance.push(temp)
							 		});
							 		this.$forceUpdate()
							 	}
							 })
						 }
						 this.isReady = true
					}
				})
			},		
			back(){
				uni.navigateBack()
			},
		},
		onLoad(option) {
			//传入单号
			this.myInfo = uni.getStorageSync('currentUser')
			this.userRightDetail = uni.getStorageSync("userRight")
			this.recordId = option.id
			this.token = uni.getStorageSync('token')
			this.state = option.state
			if(this.state == '待申请'){
				let areaId = this.myInfo.area_id
				this.createInfo.name = this.myInfo.name
				this.createInfo.company = this.myInfo.company
				this.createInfo.phone = this.myInfo.phone
				console.log("查询工作人员",areaId)
				let a = syncGetSysUsr("systemuser/area-auth/users", areaId, 1);
				a.then((res)=>{
					 if(res.data.code == 200){
						let resList = res.data.data.systemUserList
						resList.forEach((item,key) => {
							let temp = {label: "",value: ""}
							temp.label = item.name
							temp.value = item.id.toString()
							this.datalistOpe.push(temp)
						});
						this.$forceUpdate()
					}
				})
			}
		},
		mounted() {
			//如果是新建表单则不查询
			if(this.state != '待申请'){
				this.getOrder()
			}else{
				this.isReady = true
			}
		}
	}
</script>

<style>
	page{
		background-color: #ffffff
	}
	.record-id{
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 30rpx;
	}
	.state-bar{
		display: flex;
		align-items: center;
		color: #FFFFFF;
		background-color: #DD524D;
		width: 260rpx;
		justify-content: center;
		margin-left: auto;
		margin-right: 50rpx;
		font-size: 30rpx;
		border-radius: 50rpx;
		height: 50rpx;
	}
	.state-msg{
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.item-table{
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	.mix-button{
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.left-part{
		float: right;
	}
	.right-part{
		float: left;
	}
	.left-button{
		background-color: #FF0000;
		border-radius: 50rpx 0 0 50rpx;
		color: #FFFFFF;
		width: 300rpx;
		font-size: 30rpx;
	}
	.right-button{
		background-color: #0000FF;
		border-radius: 0 50rpx 50rpx 0;
		color: #FFFFFF;
		width: 300rpx;
		font-size: 30rpx;
	}
	.in-center{
		display: flex;
		flex-direction: row;
		align-items: center;
	}
	.add-button {
		border-width: 0px;
		align-items: center;
		justify-content: center;
		margin: 30rpx 0 40rpx 250rpx;
		height: 50rpx;
		width: 250rpx;
		display: flex;
		color: #22B242;
	}
	.download-text {
	  -webkit-box-sizing: content-box;
	  -moz-box-sizing: content-box;
	  box-sizing: content-box;
	  border: none;
	  font: normal 16px/1 "Times New Roman", Times, serif;
	  color: rgba(18,25,232,1);
	  text-decoration: underline;
	  -o-text-overflow: ellipsis;
	  text-overflow: ellipsis;
	  margin-left: 60rpx;
	  margin-bottom: 10rpx;
	}
	.small-title{
		margin: 20rpx 0 20rpx 50rpx;
		width: 87%;
	}
</style>
